<template>
  <div>
    <div class="app-container">
      <el-form
        :model="queryParams"
        ref="queryRef"
        v-show="showSearch"
        :inline="true"
      >
        <el-form-item label="回收编码" prop="recycleCode">
          <el-input
            v-model="queryParams.recycleCode"
            placeholder="请输入"
            clearable
            style="width: 230px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商品品牌" prop="brand">
          <el-select
            v-model="queryParams.brand"
            filterable
            reserve-keyword
            clearable
            style="width: 230px"
            allow-create
            default-first-option
            placeholder="请选择品牌"
          >
            <el-option
              v-for="item in item_brand"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品编码" prop="ref">
          <el-input
            v-model="queryParams.ref"
            placeholder="请输入"
            clearable
            style="width: 230px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商品型号" prop="model">
          <el-input
            v-model="queryParams.model"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="商品状态" prop="itemStatusList">
          <el-select
            v-model="queryParams.itemStatusList"
            placeholder="状态"
            style="width: 100px"
            multiple
            clearable
          >
            <el-option
              v-for="i in item_status"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="回收价格" prop="recyclePrice">
          <el-input
            v-model="queryParams.recyclePrice"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="成交时间">
          <el-date-picker
            v-model="salesTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            style="width: 230px"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="shortcuts"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="销售方" prop="salesPersonId">
          <el-select
            v-model="queryParams.salesPersonId"
            filterable
            remote
            reserve-keyword
            placeholder="请选择销售方"
            :remote-method="getUserOption"
            :loading="userLoading"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="到款状态" prop="paymentStatus">
          <el-select
            v-model="queryParams.paymentStatus"
            placeholder="状态"
            style="width: 80px"
            clearable
          >
            <el-option
              v-for="i in payment_status"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="到款时间">
          <el-date-picker
            v-model="paymentTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            style="width: 230px"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="shortcuts"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="到款方式" prop="paymentWayId">
          <el-select
            v-model="queryParams.paymentWayId"
            filterable
            clearable
            remote
            :remote-method="getPayment_way"
            placeholder="请选择"
            style="width: 120px"
          >
            <el-option
              v-for="item in payment_way"
              :key="item.id"
              :label="item.paymentWay"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="其他" prop="otherRemarkId">
          <el-select
            v-model="queryParams.otherRemarkId"
            filterable
            clearable
            remote
            allow-create
            :remote-method="getOtherRemark"
            placeholder="请选择"
            style="width: 230px"
          >
            <el-option
              v-for="item in otherRemarkOptions"
              :key="item.id"
              :label="item.otherRemark"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarkId">
          <el-select
            v-model="queryParams.remarkId"
            filterable
            clearable
            remote
            allow-create
            :remote-method="getSalesRemark"
            placeholder="请选择"
            style="width: 230px"
            @change="salesRemarkChange"
          >
            <el-option
              v-for="item in salesRemarkOptions"
              :key="item.id"
              :label="item.salesRemark"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户姓名" prop="customerName">
          <el-input
            v-model="queryParams.customerName"
            placeholder="请输入"
            clearable
            style="width: 230px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="打款时间">
          <el-date-picker
            v-model="recycleTime"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            style="width: 230px"
            end-placeholder="结束日期"
            :shortcuts="shortcuts"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="销售提成" prop="salesCommissions">
          <el-input
            v-model="queryParams.salesCommissions"
            placeholder="请输入"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="Search"
            @click="handleQuery"
            v-hasPermi="['erp:skesItemSales:query']"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['erp:skesItemSales:add']"
            >下架</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="Delete"
            @click="handleDelete"
            :disabled="!selectionData.length"
            v-hasPermi="['erp:skesItemSales:remove']"
            >重新下架</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['erp:skesItemSales:export']"
            >导出</el-button
          >
        </el-col>
        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
      <el-table
        v-loading="loading"
        height="60vh"
        :data="dataList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商品编码" prop="ref" align="center" />
        <el-table-column label="商品型号" prop="model" align="center" />
        <el-table-column
          label="回收价格"
          prop="recyclePrice"
          :show-overflow-tooltip="true"
          align="center"
        />
        <el-table-column label="商品状态" prop="itemStatus" align="center">
          <template #default="scope">
            <dict-tag :options="item_status" :value="scope.row.itemStatus" />
          </template>
        </el-table-column>
        <el-table-column label="回收编码" prop="recycleCode" align="center" />
        <el-table-column label="品牌" prop="brand" align="center">
          <template #default="scope">
            <dict-tag
              v-if="scope.row.brand"
              :options="item_brand"
              :value="scope.row.brand"
            />
            <span v-else>{{ scope.row.brandName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="成交价" prop="salesPrice" align="center" />
        <el-table-column
          label="成交时间"
          prop="salesTime"
          align="center"
          width="100"
        />

        <el-table-column label="销售方" prop="salesPerson" align="center" />
        <el-table-column
          label="销售提成"
          prop="salesCommissions"
          align="center"
        />
        <el-table-column label="到款状态" prop="paymentStatus" align="center">
          <template #default="scope">
            <dict-tag
              :options="payment_status"
              :value="scope.row.paymentStatus"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="到款时间"
          prop="paymentTime"
          align="center"
          width="100"
        />
        <el-table-column label="到款方式" prop="paymentWay" align="center" />
        <el-table-column label="其他" prop="otherRemark" align="center" />
        <el-table-column label="备注" prop="remark" align="center" />

        <el-table-column label="销售客户" prop="customerName" align="center" />
        <el-table-column label="回收备注" prop="recycleRemark" align="center" />
        <el-table-column
          label="商品正面图"
          prop="watchImageUrl"
          align="center"
          width="110"
        >
          <template #default="scope">
            <div style="display: flex; align-items: center; width: 50px">
              <el-image
                :src="scope.row.watchImageUrl"
                :preview-src-list="[scope.row.watchImageUrl]"
                preview-teleported
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="商品背面图"
          prop="watchImageUrlBack"
          align="center"
          width="110"
        >
          <template #default="scope">
            <div style="display: flex; align-items: center; width: 50px">
              <el-image
                :src="scope.row.watchImageUrlBack"
                :preview-src-list="[scope.row.watchImageUrlBack]"
                preview-teleported
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-tooltip
              content="修改"
              placement="top"
              v-if="scope.row.roleId !== 1"
            >
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['erp:skesItemSales:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="重新下架" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['erp:skesItemSales:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="footer-msg">
        <p>
          <i class="el-icon-warning blue-text"></i>
          数量总和:
          <span class="blue-text">{{ summaryInfo.sumCount || "N/A" }}</span>
        </p>
        <p>
          销售成交总金额:<span class="blue-text">{{
            summaryInfo.sumSalesAmount || "N/A"
          }}</span>
        </p>
        <p>
          杂项成本之和:<span class="blue-text">{{
            summaryInfo.sumOtherFee || "N/A"
          }}</span>
        </p>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <add
      v-model:visible="addParams.visible"
      :params="addParams"
      :options="payment_status"
      @refresh="getList"
    />
  </div>
</template>
<script setup name="Off_shelf">
import { listTable, delRegister } from "@/api/sales/register";
import { optionSelect } from "@/api/system/skesItem";
import { getPaymentWay, salesRemark, otherRemark } from "@/api/sales/register";
import { userOptionSelect } from "@/api/system/user";
import Add from "./add.vue";
const { proxy } = getCurrentInstance();
const dataList = ref([]);
const selectionData = ref([]);
const total = ref(0);
const loading = ref(true);
const showSearch = ref(true);
const summaryInfo = ref({});

const paymentTime = ref([]);
const salesTime = ref([]);
const recycleTime = ref([]);
const { item_brand, payment_status, item_status } = proxy.useDict(
  "item_brand",
  "payment_status",
  "item_status"
);
const addParams = ref({
  type: "add",
  visible: false,
  id: undefined,
});

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    salesPersonId: undefined,
    paymentStatus: undefined,
    paymentTime: undefined,
    paymentWayId: undefined,
    itemStatusList: undefined,
    salesTime: undefined,
    customerName: undefined,
    remark: undefined,
    salesPrice: undefined,
    recyclePrice: undefined,
    brand: undefined,
    model: undefined,
  },
});
const { queryParams, form, rules } = toRefs(data);
const shortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "最近三个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];
/** 用户下拉框 */
const userLoading = ref(false);
const userOptions = ref([]);
async function getUserOption(query) {
  if (query) {
    userLoading.value = true;
    const { data } = await userOptionSelect({ queryKey: query });
    userOptions.value = data.map((i) => {
      const { userId, nickName, userName } = i;
      return {
        value: i.userId,
        label: `${userId},${nickName},${userName}`,
        nickName,
      };
    });
    userLoading.value = false;
  }
}
getUserOption(" ");

// 其他
const otherRemarkOptions = ref([]);
async function getOtherRemark(query) {
  const { data } = await otherRemark({ queryKey: query });
  otherRemarkOptions.value = data;
}
function otherRemarkChange(val) {
  // 如果有id就传id和备注内容
  if (typeof val === "number") {
    queryParams.value.otherRemarkId = val;
    queryParams.value.otherRemark = otherRemarkOptions.value.find(
      (i) => i.id === val
    ).otherRemark;
  } else {
    queryParams.value.otherRemarkId = undefined;
  }
}
getOtherRemark(" ");

// 备注
const salesRemarkOptions = ref([]);
async function getSalesRemark(query) {
  if (query) {
    const { data } = await salesRemark({ queryKey: query });
    salesRemarkOptions.value = data;
  }
}
getSalesRemark(" ");

const payment_way = ref([]);
async function getPayment_way(query) {
  const { data } = await getPaymentWay({ queryKey: query });
  payment_way.value = data;
}

getPayment_way(" ");
/** 查询列表 */
function getList() {
  loading.value = true;
  const [beginSalesTime, endSalesTime] = salesTime.value;
  const [beginRecycleTime, endRecycleTime] = recycleTime.value;
  listTable(
    proxy.addDateRange(
      {
        ...queryParams.value,
        itemStatusList:
          queryParams.value.itemStatusList &&
          queryParams.value.itemStatusList.join(","),
        params: {
          beginSalesTime,
          endSalesTime,
          beginRecycleTime,
          endRecycleTime,
        },
      },
      paymentTime.value,
      "PaymentTime"
    )
  ).then((response) => {
    dataList.value = response.rows;
    summaryInfo.value = { ...response, rows: undefined };
    total.value = response.total;
    loading.value = false;
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  paymentTime.value = [];
  salesTime.value = [];
  recycleTime.value = [];
  handleQuery();
}
/** 导出按钮操作 */
function handleExport() {
  const [beginSalesTime, endSalesTime] = salesTime.value;
  const [beginRecycleTime, endRecycleTime] = recycleTime.value;
  const [beginPaymentTime, endPaymentTime] = paymentTime.value;
  proxy.download(
    "sales/register/export",
    {
      ...queryParams.value,
      itemStatusList:
        queryParams.value.itemStatusList &&
        queryParams.value.itemStatusList.join(","),
      params: {
        beginSalesTime,
        endSalesTime,
        beginRecycleTime,
        endRecycleTime,
        beginPaymentTime,
        endPaymentTime,
      },
    },
    `sales_${new Date().getTime()}.xlsx`
  );
}
/** 删除按钮操作 */
function handleDelete(row) {
  let ids = [],
    brands = [];
  if (row.itemId) {
    ids = row.itemId;
    brands = row.brand;
  } else {
    selectionData.value.forEach((i) => {
      ids.push(i.itemId);
      brands.push(i.brand);
    });
    ids = ids.join(",");
    brands = brands.join(",");
  }
  proxy.$modal
    .confirm('是否确认重新下架商品"' + brands + '"的数据项?')
    .then(function () {
      return delRegister(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("重新下架成功");
    })
    .catch(() => {});
}
/** 添加商品*/
function handleAdd(row) {
  /** 添加商品*/
  if (!row.id && !selectionData.value.length) {
    proxy.$modal.msgError("请选择要下架的商品");
    return;
  } else if (selectionData.value.length > 1) {
    proxy.$modal.msgError("请只选择一个商品");
    return;
  }
  const id = row.itemId ? row.itemId : selectionData.value[0].itemId;
  addParams.value = {
    id,
    type: "add",
    visible: true,
  };
}
/** 修改商品*/
function handleUpdate(row) {
  addParams.value = {
    type: "edit",
    visible: true,
    id: row.itemId,
  };
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  selectionData.value = selection.map((i) => ({
    id: i.id,
    brand: i.brand,
    itemId: i.itemId,
  }));
}
getList();
</script>
